<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import websocketService from '@/services/websocketService'
import defaultCover from '@/assets/OIP.jpg'

const router = useRouter()
const route = useRoute() // 添加route以便访问查询参数
const books = ref([])
const categories = ref([])  // 改为空数组，通过API获取
const priceFilter = ref('all')
const conditionFilter = ref('all')
const sortBy = ref('default')
const isLoading = ref(true) // 添加加载状态
const allBooks = ref([]) // 存储所有书籍数据

onMounted(() => {
  // 获取数据
  loadData()
  
  // 检查用户登录状态并连接WebSocket
  connectWebSocketIfLoggedIn()
  
  // 添加页面可见性事件监听
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onUnmounted(() => {
  // 移除页面可见性事件监听
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 处理页面可见性变化
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    // 页面变为可见时，检查WebSocket连接
    connectWebSocketIfLoggedIn()
  }
}

// 检查用户登录并连接WebSocket
const connectWebSocketIfLoggedIn = () => {
  // 检查是否有token，表示用户已登录
  const token = localStorage.getItem('token')
  if (!token) {
    console.log('用户未登录，不连接WebSocket')
    return
  }
  
  try {
    // 尝试获取用户ID
    const userData = JSON.parse(localStorage.getItem('user'))
    if (userData && userData.id) {
      console.log('用户已登录，连接WebSocket，用户ID:', userData.id)
      websocketService.connect(userData.id)
    } else {
      // 尝试从JWT解析用户ID
      try {
        const base64Url = token.split('.')[1]
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        }).join(''))
        
        const payload = JSON.parse(jsonPayload)
        if (payload && payload.sub) {
          console.log('从JWT解析的用户ID:', payload.sub)
          websocketService.connect(payload.sub)
          
          // 保存用户ID到本地存储
          localStorage.setItem('user', JSON.stringify({ id: payload.sub }))
        }
      } catch (jwtError) {
        console.error('解析JWT失败:', jwtError)
      }
    }
  } catch (error) {
    console.error('连接WebSocket失败:', error)
  }
}

// 监听路由参数的变化，用于刷新数据
watch(() => route.query.refresh, (newVal) => {
  if (newVal === 'true') {
    console.log('检测到刷新参数，重新加载数据')
    loadData()
    // 加载完成后移除查询参数，避免用户刷新页面时重复加载
    router.replace({ query: {} })
  }
})

// 加载所有数据
const loadData = async () => {
  isLoading.value = true
  try {
    await Promise.all([
      fetchCategories(),
      fetchBooks()
    ])
    
    // 当书籍数据加载完成后，预加载所有封面
    await preloadAllCovers();
  } finally {
    isLoading.value = false
  }
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await api.category.getAll()
    categories.value = response
    console.log('获取分类数据成功:', categories.value)
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
}

// 获取书籍数据
const fetchBooks = async () => {
  try {
    // 获取所有书籍，只调用一次API
    const response = await api.book.getList({})
    
    // 输出响应进行调试
    console.log('原始响应:', response)
    
    // 检查响应格式并提取数据
    if (Array.isArray(response)) {
      // 如果是数组，直接使用
      allBooks.value = response
      console.log('获取书籍数据成功 (数组格式):', allBooks.value)
    } else if (response && response.code == 200 && response.data) {
      // 如果是包含code和data的对象，则使用response.data
      allBooks.value = response.data
      console.log('获取书籍数据成功 (对象格式):', allBooks.value)
    } else {
      console.error('获取书籍数据失败: 返回格式不正确', response)
      allBooks.value = [] // 失败时设置为空数组
    }
  } catch (error) {
    console.error('获取书籍数据失败:', error)
    allBooks.value = [] // 出错时设置为空数组
  }
}

// 价格区间参数映射
const getPriceRange = (book, range) => {
  const price = parseFloat(book.price);
  switch(range) {
    case '0-20': return price <= 20;
    case '20-50': return price > 20 && price <= 50;
    case '50-100': return price > 50 && price <= 100;
    case '100+': return price > 100;
    default: return true; // 全部价格
  }
}

// 品相过滤
const getCondition = (book, condition) => {
  switch(condition) {
    case 'new': return book.book_condition === 'new';
    case 'good': return book.book_condition === 'good';
    case 'used': return book.book_condition === 'used';
    default: return true; // 全部品相
  }
}

// 监听筛选和排序条件变化
watch([priceFilter, conditionFilter, sortBy], () => {
  console.log('筛选条件变化:', {
    价格: priceFilter.value,
    品相: conditionFilter.value,
    排序: sortBy.value
  });
})

// 前端筛选和排序
const filteredBooks = computed(() => {
  if (allBooks.value.length === 0) return [];
  
  console.log('执行筛选，原始数据数量:', allBooks.value.length);
  
  // 先筛选
  let result = allBooks.value.filter(book => {
    const priceMatches = getPriceRange(book, priceFilter.value);
    const conditionMatches = getCondition(book, conditionFilter.value);
    return priceMatches && conditionMatches;
  });
  
  // 再排序
  if (sortBy.value === 'price-asc') {
    result.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
  } else if (sortBy.value === 'price-desc') {
    result.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
  } else if (sortBy.value === 'condition') {
    // 品相优先级：new > good > used
    const conditionValue = (condition) => {
      switch(condition) {
        case 'new': return 3;
        case 'good': return 2;
        case 'used': return 1;
        default: return 0;
      }
    };
    
    result.sort((a, b) => conditionValue(b.book_condition) - conditionValue(a.book_condition));
  }
  
  console.log('筛选后数据数量:', result.length);
  return result;
})

const viewBookDetails = (bookId) => {
  router.push(`/book/${bookId}`)
}

const filterByCategory = (categoryId) => {
  // 检查分类ID的有效性
  if (!categoryId) {
    console.error('无效的分类ID');
    return;
  }
  
  // 为CategoryView.vue提供分类名称，避免再次请求
  const category = categories.value.find(c => c.id === categoryId);
  const categoryName = category ? category.name : '';
  
  router.push({
    path: '/category',
    query: { 
      id: categoryId,
      name: categoryName
    }
  });
}

// 获取封面URL
const getCoverUrl = (book) => {
  if (!book || !book.cover) {
    console.log('无封面数据，使用默认封面');
    return defaultCover;
  }
  
  try {
    // 检查是否为相对路径，添加基础URL
    if (typeof book.cover === 'string') {
      if (!book.cover.startsWith('http')) {
        // 对路径进行URL编码，确保特殊字符不会导致问题
        const encodedPath = book.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
        console.log('编码后的封面路径:', encodedPath);
        return `http://localhost:8080/${encodedPath}`;
      }
      return book.cover;
    }
    
    // 如果book.cover不是字符串，使用默认封面
    console.log('封面格式不正确，使用默认封面');
    return defaultCover;
  } catch (error) {
    console.error('获取封面URL时出错:', error);
    return defaultCover;
  }
}

// 添加一个函数来预加载所有书籍封面
const preloadAllCovers = async () => {
  console.log('开始预加载所有书籍封面');
  const promises = filteredBooks.value.map(book => {
    const url = getCoverUrl(book);
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => resolve(); // 即使失败也resolve，不阻塞
      img.src = url;
    });
  });
  
  // 等待所有图片预加载完成
  await Promise.all(promises);
  console.log('所有封面预加载完成');
}
</script>

<template>
  <div class="home">
    <NavBar />
    <main class="container">
      <LoadingSpinner v-if="isLoading" message="正在加载书籍数据..." />
      
      <div v-else class="home-layout">
        <div class="sidebar">
          <h3>分类浏览</h3>
          <div class="category-list">
            <div class="category-item" v-for="category in categories" :key="category.id" @click="filterByCategory(category.id)">
              {{ category.name }}
            </div>
          </div>
          
          <div class="sidebar-section">
            <h3>快速筛选</h3>
            <div class="filter-group">
              <label>价格区间:</label>
              <select v-model="priceFilter">
                <option value="all">全部价格</option>
                <option value="0-20">20元以下</option>
                <option value="20-50">20-50元</option>
                <option value="50-100">50-100元</option>
                <option value="100+">100元以上</option>
              </select>
            </div>
            
            <div class="filter-group">
              <label>品相:</label>
              <select v-model="conditionFilter">
                <option value="all">全部品相</option>
                <option value="new">几乎全新</option>
                <option value="good">品相良好</option>
                <option value="used">有使用痕迹</option>
              </select>
            </div>
            
            <div class="filter-group">
              <label>排序方式:</label>
              <select v-model="sortBy">
                <option value="default">默认排序</option>
                <option value="price-asc">价格从低到高</option>
                <option value="price-desc">价格从高到低</option>
                <option value="condition">品相优先</option>
              </select>
            </div>
          </div>
        </div>
        
        <div class="main-content">
          <section class="banner">
            <h2>校园二手书交易平台</h2>
            <p>低价好书，轻松交易，让知识流动起来</p>
          </section>
          
          <section>
            <div class="section-header">
              <h3>热门分类</h3>
            </div>
            <div class="categories-row">
              <div class="category-card" v-for="category in categories.slice(0, 6)" :key="category.id" @click="filterByCategory(category.id)">
                <div class="category-icon">📚</div>
                <div class="category-name">{{ category.name }}</div>
              </div>
            </div>
          </section>
          
          <section class="book-list">
            <div class="section-header">
              <h3>最新上架</h3>
              <router-link to="/category" class="view-all">查看全部 &rarr;</router-link>
            </div>
            <div class="books-grid">
              <div class="book-card" v-for="book in filteredBooks" :key="book.id" @click="viewBookDetails(book.id)">
                <div class="book-cover">
                  <img :src="getCoverUrl(book)" :alt="book.title">
                </div>
                <div class="book-info">
                  <h4>{{ book.title }}</h4>
                  <p class="book-author">{{ book.author }}</p>
                  <p class="book-price">¥{{ book.price }}</p>
                  <p class="book-seller">卖家: {{ book.seller_name }}</p>
                  <div class="book-tags">
                    <span v-if="book.book_condition === 'new'" class="tag tag-new">几乎全新</span>
                    <span v-else-if="book.book_condition === 'good'" class="tag tag-good">品相良好</span>
                    <span v-else-if="book.book_condition === 'used'" class="tag tag-used">有使用痕迹</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 1.5rem;
}

.home-layout {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 2rem;
}

.sidebar {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1.5rem;
  height: fit-content;
  position: sticky;
  top: 80px;
}

.sidebar h3 {
  font-size: 1.2rem;
  color: #1f2937;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 2rem;
}

.category-item {
  padding: 0.5rem 1rem;
  background-color: #f3f4f6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.category-item:hover {
  background-color: #e5e7eb;
  transform: translateX(5px);
}

.sidebar-section {
  margin-top: 1.5rem;
}

.filter-group {
  margin-bottom: 1rem;
}

.filter-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #4b5563;
  font-weight: 500;
  font-size: 0.95rem;
}

.filter-group select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: white;
  font-size: 0.9rem;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.banner {
  text-align: center;
  padding: 3rem 2rem;
  background-color: #e0f2fe;
  border-radius: 8px;
  background-image: linear-gradient(120deg, #e0f2fe, #dbeafe);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.banner h2 {
  font-size: 2rem;
  color: #1e40af;
  margin-bottom: 0.75rem;
  font-weight: bold;
}

.banner p {
  font-size: 1.1rem;
  color: #4b5563;
  max-width: 600px;
  margin: 0 auto;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.section-header h3 {
  font-size: 1.4rem;
  color: #1f2937;
  margin: 0;
}

.view-all {
  color: #3b82f6;
  font-size: 0.9rem;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 1.5rem;
}

.book-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
  background-color: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.book-cover {
  height: 200px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.book-card:hover .book-cover img {
  transform: scale(1.05);
}

.book-info {
  padding: 1rem;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.book-info h4 {
  margin: 0 0 0.5rem;
  font-size: 1rem;
  color: #1f2937;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-author {
  color: #6b7280;
  margin: 0.25rem 0;
  font-size: 0.85rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-price {
  font-weight: bold;
  color: #ef4444;
  margin: 0.5rem 0;
  font-size: 1.1rem;
}

.book-seller {
  color: #6b7280;
  font-size: 0.85rem;
  margin: 0.25rem 0;
}

.book-tags {
  display: flex;
  gap: 0.5rem;
  margin-top: auto;
  padding-top: 0.5rem;
}

.tag {
  font-size: 0.7rem;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
}

.tag-new {
  background-color: #dcfce7;
  color: #166534;
}

.tag-good {
  background-color: #fef3c7;
  color: #92400e;
}

.tag-used {
  background-color: #fee2e2;
  color: #991b1b;
}

.categories-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.category-card {
  background-color: white;
  border-radius: 8px;
  padding: 1rem;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.2s;
}

.category-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.category-icon {
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
  color: #3b82f6;
}

.category-name {
  font-weight: 500;
  color: #1f2937;
}

@media (max-width: 1024px) {
  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}

@media (max-width: 768px) {
  .home-layout {
    grid-template-columns: 1fr;
  }
  
  .sidebar {
    position: static;
    margin-bottom: 1.5rem;
  }
  
  .category-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
  }
  
  .book-cover {
    height: 180px;
  }
}
</style>
